package com.example.demo.service;

import io.netty.channel.Channel;
import lombok.Data;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.Queue;

@Component
public class WebSocketQueue {

    private final Queue<QueueEntry> queue = new LinkedList<>();

    //添加websocket连接到队列
    public synchronized void addToQueue(Channel channel) {
        long waitStart = System.currentTimeMillis();
        queue.add(new QueueEntry(channel, waitStart));
    }

    //获取当前排队人数
    public synchronized int getQueueSize() {
        return queue.size();
    }

    //获取当前排队列表(包含等待时长)
    public synchronized String getQueueDetails() {
        StringBuilder details = new StringBuilder();
        for (QueueEntry entry : queue) {
            long waitTime = (System.currentTimeMillis() - entry.getWaitStart()) / 1000;
            details.append("Client:").append(entry.getChannel().remoteAddress()).append("| Wait Time: ").append(waitTime).append("s\n");
        }
        return details.toString();
    }

    //获取并移除队列中的第一个websocket连接
    public synchronized Channel removeFromQueue() {
        return queue.poll() != null ? queue.peek().getChannel() : null;
    }

    @Data
    private static class QueueEntry{
        private final Channel channel;
        private final long waitStart;

        public QueueEntry(Channel channel, long waitStart) {
            this.channel = channel;
            this.waitStart = waitStart;
        }
    }
}
